#!/bin/bash

# 确保日志函数
log() {
    echo "[INFO] $1"
}

# 检查是否为 root 用户
is_root() {
    [ "$EUID" -eq 0 ]
}

# 检查并安装包的函数
install_package() {
    local package_name=$1

    if ! dpkg -l | grep -q "$package_name"; then
        log "$package_name 未找到，正在安装..."
        if is_root; then
            install_cmd="apt-get"
        else
            install_cmd="sudo apt-get"
        fi

        $install_cmd update
        $install_cmd install -y "$package_name"
    else
        log "$package_name 已安装"
    fi
}

# 检查并安装 curl
check_and_install_curl() {
    if ! command -v curl &> /dev/null; then
        install_package "curl"
    else
        log "curl 已安装"
    fi
}

# 检查并安装 libgl1-mesa-glx
check_and_install_libgl() {
    install_package "libgl1-mesa-glx"
}

# 定义全局变量
ROOT_DIR="$HOME/.labelapp"
CONDA_DIR="$ROOT_DIR/miniconda"
NODE_DIR="$ROOT_DIR/nodejs"
LABELAPP_DIR="$ROOT_DIR/labelapp"
TEMP_DIR="$ROOT_DIR/tmp"
SCRIPTS_DIR="$ROOT_DIR/scripts"
BOS_BASE_URL="https://label-anything.bd.bcebos.com/labelapp/server"
REMOTE_INDEX_URL="${BOS_BASE_URL}/VERSION"

# 函数定义

get_remote_version() {
    curl -s $REMOTE_INDEX_URL | tr -d '\n'
}

get_local_version() {
    if [ -f "$ROOT_DIR/VERSION" ]; then
        cat "$ROOT_DIR/VERSION" | tr -d '\n'
    else
        echo ""
    fi
}

install_labelapp() {
    local remote_version=$(get_remote_version)
    local local_version=$(get_local_version)

    log "远程版本: $remote_version"
    log "本地版本: $local_version"

    if [ "$local_version" != "$remote_version" ]; then
        log "版本不一致，准备更新..."

        if [ -d "$LABELAPP_DIR" ]; then
            touch "$LABELAPP_DIR/exit.flag" && log "已触发服务退出"
        fi

        wait_for_exit

        rm -rf "$LABELAPP_DIR"
        mkdir -p "$LABELAPP_DIR" "$TEMP_DIR"

        local zip_path="$TEMP_DIR/dist-${remote_version}.zip"
        wget -O "$zip_path" "${BOS_BASE_URL}/dist-${remote_version}.zip"
        unzip -o "$zip_path" -d "$LABELAPP_DIR"

        # 检查 yarn 是否已安装，如果未安装则安装 yarn
        if ! command -v yarn &> /dev/null; then
            log "yarn 未安装，正在安装 yarn..."
            "$NODE_DIR/bin/npm" install -g yarn --registry=http://registry.npm.taobao.org
        fi

        # 设置 yarn 的镜像源为淘宝源
        yarn config set registry http://registry.npm.taobao.org

        # 使用 yarn 安装依赖
        cd "$LABELAPP_DIR"
        yarn install

        echo "$remote_version" > "$ROOT_DIR/VERSION"
        rm -rf "$zip_path"

        log "安装或更新完成"
    else
        log "本地版本和远程版本一致，无需更新"
    fi
}

wait_for_exit() {
    local timeout=30
    local interval=2
    local elapsed=0

    local pid=$(pgrep -f "node ${LABELAPP_DIR}/start.js" || echo "")
    while [ -n "$pid" ] && [ $elapsed -lt $timeout ]; do
        if ps -p $pid > /dev/null; then
            log "等待进程 $pid 退出..."
            sleep $interval
            elapsed=$((elapsed + interval))
        else
            log "服务已退出"
            break
        fi
    done

    if [ -n "$pid" ] && [ $elapsed -ge $timeout ]; then
        log "进程未在超时时间内退出"
        exit 1
    fi
}

configure_channels() {
    local conda_path="$CONDA_DIR/bin/conda"
    $conda_path config --set custom_channels.conda-forge https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.msys2 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.bioconda https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.menpo https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.pytorch https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.pytorch-lts https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.simpleitk https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
    $conda_path config --set custom_channels.deepmodeling https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/
    $conda_path config --add default_channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2'
    $conda_path config --add default_channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r'
    $conda_path config --add default_channels 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main'
    log "Channels configured successfully"
}

install_conda() {
    local arch=$(uname -m)
    local miniconda_script

    if [[ "$arch" == "x86_64" ]]; then
        miniconda_script="Miniconda3-latest-Linux-x86_64.sh"
    else
        miniconda_script="Miniconda3-latest-Linux-armv7l.sh"
    fi

    wget "https://repo.anaconda.com/miniconda/$miniconda_script" -O miniconda.sh
    bash miniconda.sh -b -p "$CONDA_DIR"
    export PATH="$CONDA_DIR/bin:$PATH"
    source "$CONDA_DIR/bin/activate"
    conda init
    configure_channels

    rm -f miniconda.sh
}

install_node() {
    local arch=$(uname -m)
    local node_binary
    local glibc_version=$(ldd --version | awk '/ldd/{print $NF}')

    echo "Detected GLIBC version: $glibc_version"

    # 根据GLIBC版本选择Node.js版本
    if [[ "$(printf '%s\n' "2.28" "$glibc_version" | sort -V | head -n1)" == "2.28" ]]; then
        echo "GLIBC version is >= 2.28, installing Node.js v18.x"
        if [[ "$arch" == "x86_64" ]]; then
            node_binary="node-v18.17.1-linux-x64.tar.xz"
        else
            node_binary="node-v18.17.1-linux-armv7l.tar.xz"
        fi
        node_url="https://nodejs.org/dist/v18.17.1/$node_binary"
    else
        echo "GLIBC version is < 2.28, installing Node.js v16.x"
        if [[ "$arch" == "x86_64" ]]; then
            node_binary="node-v16.20.2-linux-x64.tar.xz"
        else
            node_binary="node-v16.20.2-linux-armv7l.tar.xz"
        fi
        node_url="https://nodejs.org/dist/v16.20.2/$node_binary"
    fi

    # 下载并安装Node.js
    echo "Downloading Node.js: $node_binary"
    wget "$node_url" -O node.tar.xz
    mkdir -p "$NODE_DIR"
    tar -xf "node.tar.xz" -C "$NODE_DIR" --strip-components=1

    # 清理临时文件
    rm -f node.tar.xz

    echo "Node.js installation complete!"
    echo "Node.js version:"
    "$NODE_DIR/bin/node" --version

    # 将Node.js添加到PATH
    if [[ ":$PATH:" != *":$NODE_DIR/bin:"* ]]; then
        echo "Adding Node.js to PATH..."
        export PATH="$NODE_DIR/bin:$PATH"
        echo "export PATH=\"$NODE_DIR/bin:\$PATH\"" >> ~/.bashrc
        echo "Node.js has been added to your PATH. Please run 'source ~/.bashrc' or restart your shell to apply changes."
    else
        echo "Node.js is already in your PATH."
    fi
}

check_and_install_software() {
    local software=$1
    local check_command=$2
    local install_function=$3

    if eval "$check_command"; then
        log "$software 已安装"
    else
        eval "$install_function"
    fi
}

main() {
    check_and_install_curl
    check_and_install_libgl

    SOFTWARE_LIST=("conda" "node" "labelapp")
    for software in "${SOFTWARE_LIST[@]}"; do
        case $software in
            "conda")
                check_and_install_software "conda" "[ -d '$CONDA_DIR' ]" "install_conda"
                ;;
            "node")
                check_and_install_software "node" "[ -d '$NODE_DIR' ] && [ -x '$NODE_DIR/bin/node' ]" "install_node"
                ;;
            "labelapp")
                install_labelapp
                ;;
            *)
                log "未知软件 $software"
                ;;
        esac
    done

    # 执行另一个脚本
    # bash "$SCRIPTS_DIR/system_info.sh"
}

main